package com.example.jussi.asynctaskdemo;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    TextView textView;
    Button button;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyAsync myAsync = new MyAsync(MainActivity.this);
                myAsync.execute(new Integer(0));
            }
        });
    }

    private class MyAsync extends AsyncTask<Integer, Integer, String>{
        Context context;
        public MyAsync(Context context){
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "onPreExecute: ");
            super.onPreExecute();
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("提示");
            progressDialog.setMessage("任务正在进行中……");
            progressDialog.setMax(100);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();
            progressDialog.setProgress(20);
            textView.setText("任务正在进行中……");
        }

        @Override
        protected String doInBackground(Integer... integers) {
            Log.d(TAG, "doInBackground: ");
            int i = integers[0];
            while (i<100){
                i++;
                publishProgress(i);     //提交到 onProgressUpdate
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "任务已完成";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {    //values 来自 i
            Log.d(TAG, "onProgressUpdate: ");
            super.onProgressUpdate(values);
            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String s) {    //String 来自 doInBackground（）的返回值
            Log.d(TAG, "onPostExecute: ");
            super.onPostExecute(s);
            progressDialog.dismiss();
            textView.setText(s);
        }
    }
}
